/** *
 *
 * 云打印交互协议（https://support-cnkuaidi.taobao.com/doc.htm#?docId=107014&docType=1）
 *
 */

/** *
 *
 * 获取请求的UUID，指定长度和进制,如
 * getUUID(8, 2)   //"01001010" 8 character (base=2)
 * getUUID(8, 10) // "47473046" 8 character ID (base=10)
 * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
 *
 */
function getUUID(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  var uuid = []; var i
  radix = radix || chars.length
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  } else {
    var r
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random() * 16
        uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

export class socketClient {
  constructor(options) {
    this.socket = null
    this.serviceUrl = options.url
    this.callback = options.received
  }
  doConnect(msg) {
    this.socket = new WebSocket(this.serviceUrl)
    // 建立连接
    this.socket.onopen = e => {
      console.log('Socket连接成功--->', e)
      // 给后台发送数据
      if (msg) {
        // return this.socket.send(JSON.stringify(msg))
        return this.getResult(msg)
      }
    }
    // 接受服务器返回的信息
    this.socket.onmessage = e => {
      if (typeof this.callback === 'function') {
        return this.callback(e.data)
      } else {
        console.error('参数的类型必须为函数')
      }
    }
    // 关闭连接
    this.socket.onclose = e => {
      console.warn('socket连接已关闭--->', e)
    }
    // 连接错误
    this.socket.onerror = e => {
      console.error('socket连接发生错误--->', e)
    }
  }
  sendCommand(msg) {
    msg.task.taskID = getUUID(8, 10)
    if (!this.socket) {
      this.doConnect(msg)
      return
    }
    if (this.socket.readyState !== 1) {
      this.doConnect(msg)
      return
    }
    this.socket.send(JSON.stringify(msg))
  }
  close() {
    return this.socket.close()
  }

  // 获取打印机列表
  getPrinters() {
    const parms = {
      cmd: 'getPrinters',
      requestID: getUUID(8, 10),
      version: '1.0'
    }
    return new Promise((resolve, reject) => {
      try {
        this.socket.send(JSON.stringify(parms))
        this.socket.onmessage = e => {
          resolve(e.data)
        }
      } catch (err) {
        reject(err)
      }
    })
  }
  // 设置打印机配置
  setPrinterConfig(name = 'QR-488BT LABEL') {
    const parms = {
      cmd: 'setPrinterConfig',
      requestID: getUUID(8, 10),
      version: '1.0',
      printer: {
        name,
        needTopLogo: false,
        needBottomLogo: false,
        horizontalOffset: 0.5,
        verticalOffset: 0.7,
        forceNoPageMargins: true,
        autoPageSize: true,
        orientation: 0,
        autoOrientation: false,
        paperSize: {
          width: 100,
          height: 180
        }
      }
    }
    return new Promise((resolve, reject) => {
      try {
        this.socket.send(JSON.stringify(parms))
        this.socket.onmessage = e => {
          resolve(e.data)
        }
      } catch (err) {
        reject(err)
      }
    })
  }
  // 顺序执行，获取打印机列表 --> 设置打印机配置 --> 给打印机下发打印任务
  getResult(msg) {
    Promise.resolve().then(() => {
      return this.getPrinters()
    })
      .then((response) => {
        if (response) {
          const res = JSON.parse(response)
          if (res.status === 'success') {
            return this.setPrinterConfig(res.defaultPrinter)
          } else {
            console.error(res.msg)
          }
        }
      })
      .then((response) => {
        if (response) {
          const res = JSON.parse(response)
          if (res.status === 'success') {
            return this.sendCommand(msg)
          } else {
            console.error(res.msg)
          }
        }
      })
  }
  // 处理要打印的数据
  processingData(listData, cb) {
    const documents = []
    const printObject = {
      cmd: 'print',
      requestID: new Date().getTime(),
      version: '1.0',
      task: {
        preview: false,
        printer: '',
        notifyMode: 'allInOne',
        previewType: 'pdf',
        documents: []
      }
    }
    for (const item of listData) {
      const expressBillData = {
        documentID: item.code,
        contents: [
          {
            data: {
              recipient: {
                address: {
                  city: item.receiverCity,
                  detail: item.receiverDetailAddress,
                  district: item.receiverDistrict,
                  province: item.receiverProvince,
                  town: ''
                },
                mobile: item.receiverMobile,
                name: item.receiverName,
                phone: ''
              },
              routingInfo: {
                routeCode: '123A-456-789'
              },
              sender: {
                address: {
                  city: item.senderCity,
                  detail: item.senderDetailAddress,
                  district: item.senderDistrict,
                  province: item.senderProvince,
                  town: ''
                },
                mobile: item.senderMobile,
                name: item.senderName,
                phone: ''
              },
              waybillCode: item.waybillCode
            },
            templateURL:
              'http://cloudprint.cainiao.com/cloudprint/template/getStandardTemplate.json?template_id=101&version=4'
          },
          {
            templateURL: 'http://cloudprint.cainiao.com/template/customArea/13450842/4'
          }
        ]
      }
      documents.push(expressBillData)
    }
    printObject.task.documents = documents
    cb && cb(printObject)
  }
}
